import 'dart:async';

import 'package:flutter/widgets.dart' hide Banner;
import 'package:flutter_hooks/flutter_hooks.dart' hide Store;
import 'package:todo_app/controllers/definitions/RtcRoomModel.dart';
import 'package:todo_app/utils/call/CallFms.dart';
import 'package:todo_app/utils/call/CallHelper.dart';
import 'package:todo_app/utils/call/contexts/ConnectingUIContext.dart';
import 'package:todo_app/utils/call/contexts/IdleContext.dart';
import 'package:todo_app/utils/webrtc/RTCSingleRoomPage.dart';


GlobalRtcVideoController useGlobalRtcVideoController() {
  return use( const _GlobalRtcVideoControllerHook());
}

class _GlobalRtcVideoControllerHook extends Hook<GlobalRtcVideoController> {
  const _GlobalRtcVideoControllerHook();

  @override
  _GlobalRtcVideoControllerState createState() =>_GlobalRtcVideoControllerState();
}

class _GlobalRtcVideoControllerState extends HookState<GlobalRtcVideoController, _GlobalRtcVideoControllerHook> {
  late GlobalRtcVideoController controller;
  late StreamSubscription<CallTransitionEvent> subscription;
  late StreamSubscription<CallHelperEvent> subscription2;
  @override
  void initHook() {
    controller = GlobalRtcVideoController();
    CallHelper.init();
    subscription = CallHelper.callFms.eventBus.on<CallTransitionEvent>().listen((CallTransitionEvent event) async {
      if(event.type == CallTransitionType.CONNECTING || event.type == CallTransitionType.CALL_IN || event.type == CallTransitionType.CALL_OUT) {
        ConnectingUIContext context = event.payload as ConnectingUIContext;
        controller.show(context.room);
        controller.lastRoom = context.room;
        setState(() { });
      }
      if(event.type == CallTransitionType.DISCONNECTED) {
        IdleContext context = event.payload as IdleContext;
        if(context.chatRoomId == controller.lastRoom?.room_id) {
          controller.hide();
          setState(() { });
        }
      }
    });
    subscription2 = CallHelper.eventBus.on<CallHelperEvent>().listen((CallHelperEvent event) async {
      if(event.type == CallHelperEventType.CHANGE_APP_SATE) {
        setState(() { });
      }
    });
    super.initHook();
  }

  @override
  void dispose() {
    controller.dispose();
    subscription.cancel();
    subscription2.cancel();
    CallHelper.dispose();
    super.dispose();
  }

  @override
  GlobalRtcVideoController build(BuildContext context) {
    return controller;
  }
}

class GlobalRtcVideoController {
  OverlayEntry? overlayEntry;
  RtcRoomModel? lastRoom;
  void show(RtcRoomModel room) {
    if(lastRoom?.room_id != room.room_id) {
      overlayEntry = showSingleChatRoom();
    }
  }

  void hide() {
    lastRoom = null;
    overlayEntry?.remove();
  }

  dispose() {
    lastRoom = null;
    overlayEntry?.remove();
  }
}
